﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using CodeDynamiksEngine;
using MESCodeFile;
using LiveStateSystem;

namespace mes_tublay
{
    public partial class frmUserManager : Form
    {
        CodeProcessor proc = new CodeProcessor(ThreadingMode.Normal);
        DataCache cache = new DataCache("USERDATA");
        DataCache cachepriv = new DataCache("USERPRIVILEGE");
        
        bool hasImage = false, isAddNew = true, isEditorMode = false, isAuthOk=false;
        int userToEdit = -1;
        string _uid = "", _pwd = "";

        public frmUserManager()
        {
            InitializeComponent();
            InitializeFrameSliderForm();
            this.FormClosing += new FormClosingEventHandler(delegate
            {
                if (hasImage)
                {
                    //imgUser.Image.Dispose();
                    imgUser.Image = mes_tublay.Properties.Resources.DefaultProfile;
                    hasImage = false;
                }
            });
        }
        private void InitializeForm()
        {
            //Form is initialized
            isEditorMode = true;

            //Register Events
            DoGUIEvents();
            DoCodeProcessor();
            //Initialize the CodeProcessor
            InitCodeProc();
            //Initialize the save state
            InitializeSaveState();
        }
        //Handle GUI events
        void DoGUIEvents()
        {
            /////////////////////////////////////////////////
            //Image processing
            /////////////////////////////////////////////////
            btnAttachImage.Click += new EventHandler(delegate
            {
                //Instantiate an Image Capture form
                frmImageCapture imgCap = new frmImageCapture();
                //Initialize the form
                imgCap.InitializeForm();
                //Add Post Process Text.
                imgCap.AddPostProcessText(txtUID.Text);
                //Show the form
                imgCap.ShowDialog();
                //Check if the user has taken an image, if so, pass it to the picture box.
                if (imgCap.HasTakenImage)
                {
                    imgUser.Image = imgCap.GetImage();
                    imgCap.SaveToFileBuffer(Common.LOCPATH, CurrentUser.USERIDNUMBER + Const.USERMANAGERIMG);
                    hasImage = true;
                }
            });
            btnRemoveImage.Click += new EventHandler(delegate
            {
                //Confirmation for image removal
                if (Confirm.Question("Image Removal", "Remove attached image?") == System.Windows.Forms.DialogResult.Yes)
                {
                    //Set the image into blank bitmap
                    if (hasImage)
                    {
                        //imgUser.Image.Dispose();
                        imgUser.Image = mes_tublay.Properties.Resources.DefaultProfile;
                        hasImage = false;
                    }
                }
            });
            imgUser.DoubleClick += new EventHandler(delegate
            {
                //Show the image to the viewer.
                frmImageViewer imgVw = new frmImageViewer();
                imgVw.SetImage((Bitmap)imgUser.Image);
                imgVw.ShowDialog();
            });
            ////////////////////////////////////////////
            //Buttons
            ///////////////////////////////////////////
            btnAddNew.Click += new EventHandler(delegate
            {
                //GUI automation
                lstUsers.Enabled = false;
                btnAddNew.Enabled = false;
                btnDeactivate.Enabled = false;
                grpUserDetails.Enabled = true;
                txtUID.Focus();
                isAddNew = true;
                if (isEditorMode)
                {
                    if (!state.Running) state.Run();
                }
            });
            btnSave.Click += new EventHandler(delegate
            {
                //Check input before saving to database to prevent dirty data.
                if (txtUID.Text.Trim().Length < 5)
                {
                    Confirm.Error("Input Error", "Username must be atleast 5(five) characters long.");
                    return;
                }
                if (txtPWD.Text.Length < 5)
                {
                    Confirm.Error("Input Error", "Password must be atleast 5(five) characters long.");
                    return;
                }
                if (lstPrivilege.Items.Count == 0)
                {
                    Confirm.Error("Input Error", "An account must have atleast 1(one) privilege included.");
                    return;
                }

                grpUserDetails.Enabled = false;
                btnAddNew.Enabled = false;

                SaveUserData();
            });
            btnCancel.Click += new EventHandler(delegate
            {
                if (Confirm.Question("Cancel User", "Cancel the user profile creation?") == System.Windows.Forms.DialogResult.No) return;
                Clear();

                lstUsers.Enabled = true;
                btnAddNew.Enabled = true;
                grpUserDetails.Enabled = false;
                //Set the image into blank bitmap
                if (hasImage)
                {
                    //imgUser.Image.Dispose();
                    imgUser.Image = mes_tublay.Properties.Resources.DefaultProfile;
                    hasImage = false;
                }
                if (isEditorMode)
                {
                    if (state.Running) state.Stop();
                }
            });
            btnAddPriv.Click += new EventHandler(delegate
            {
                if (lstPrivilege.Items.IndexOf(txtPrivilege.Text) != -1)
                {
                    Confirm.Error("Privilege Error", "This will create duplicate privilege for this user.");
                    return;
                }
                if (txtPrivilege.SelectedIndex == -1)
                {
                    Confirm.Error("Privilege Error", "Please select a privilege for the user first.");
                    return;
                }
                lstPrivilege.Items.Add(txtPrivilege.Text);
            });
            btnRemPriv.Click += new EventHandler(delegate
            {
                lstPrivilege.Items.RemoveAt(lstPrivilege.SelectedIndex);
                btnRemPriv.Enabled = false;
            });
            btnDeactivate.Click += new EventHandler(delegate
            {
                grpUserDetails.Enabled = false;
                btnAddNew.Enabled = false;
                DeactivateAccount();
            });
            ///////////////////////////////////////////////////
            //ListBox
            ///////////////////////////////////////////////////
            lstPrivilege.Click += new EventHandler(delegate
            {
                //When the user clicks the privilege list, enable the remove privilege button,
                if (lstPrivilege.SelectedIndex == -1) return;
                btnRemPriv.Enabled = true;
            });
            
            lstUsers.DoubleClick += new EventHandler(delegate
            {
                //When the user double clicks the user profile, load the profile
                if (lstUsers.SelectedIndices.Count == 0) return;
                cache.SetActivePage(0);
                userToEdit = lstUsers.SelectedIndices[0];
                
                btnAddNew.Enabled = false;
                btnDeactivate.Enabled = true;
                lstUsers.Enabled = false;
                grpUserDetails.Enabled = false;
                isAddNew = false;
                LoadUserData();
            });
        }
        //Handle processor events
        void DoCodeProcessor()
        {
            proc.ProcessCompleted += new EventHandler(delegate
            {
                proc.SafeCall(this, delegate
                {
                    if (proc.State == ProcessorFlag.DataRdyErr ||
                        proc.State == ProcessorFlag.ReadyErr)
                    {
                        if(isEditorMode) MessageBox.Show(proc.GetProcessorMessage, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        //Function specific action
                        switch (proc.GetLastProcessName())
                        {
                            case "SAVE":
                                grpUserDetails.Enabled = true;
                                break;
                            case "GETUSERDATA":
                                Confirm.Generic("Login Error", "There was problem retrieving your data.", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                                try
                                {
                                    proc.DataFetch(out cachepriv);
                                    cachepriv.SetActivePage(0);
                                    cachepriv.TessellateColumn("fPrivilege");
                                    ShowUserData();
                                    if (isEditorMode)
                                    {
                                        if (!state.Running) state.Run();
                                    }
                                }
                                catch
                                {
                                    Confirm.Error("Login Error", "There was an error connecting to the server.\r\nPlease check your connection.");
                                    this.Close();
                                }
                                break;
                        }
                        proc.ClearErrorFlag();
                        return;
                    }
                    if (proc.State == ProcessorFlag.Error)
                    {
                        switch (proc.GetLastProcessName())
                        {
                            case "LOADPRIV":
                                Confirm.Error("Login Error", "There was an error connecting to the server.\r\nPlease check your connection.");
                                this.Close();
                                break;
                        }
                        proc.ClearErrorFlag();
                        return;
                    }
                    switch (proc.GetLastProcessName())
                    {
                        case "INITPROC":
                            if (isEditorMode)
                            {
                                btnAddNew.Enabled = true;
                                lstUsers.Enabled = true;
                            }
                            LoadGUIData();
                            break;
                        case "LOADPRIV":
                            proc.DataFetch(out cache);

                            //Display data to control if editor mode
                            if (isEditorMode)
                            {
                                FetchData();
                            }
                            else
                            {
                                VerifyCredentials();
                            }
                            break;
                        case "SAVE":
                            //Fetch the updated user table.
                            proc.DataFetch(out cache);
                            FetchData();

                            //Display info that the save is successful.
                            Confirm.Info("Data Save", "User profile successfully saved.");
                            Clear();

                            //Do GUI automation
                            lstUsers.Enabled = true;
                            btnAddNew.Enabled = true;
                            grpUserDetails.Enabled = false;
                            if (isEditorMode)
                            {
                                if (state.Running) state.Stop();
                            }
                            break;
                        case "GETUSERDATA":
                            proc.DataFetch(out cachepriv);
                            cachepriv.SetActivePage(0);
                            cachepriv.TessellateColumn("fPrivilege");
                            ShowUserData();
                            if (isEditorMode)
                            {
                                if (!state.Running) state.Run();
                            }
                            break;
                    }
                });//SafeCall
            });//ProcessCompleted
        }
        //Fetch the User List and Privilege
        void FetchData()
        {
            //Obtain the User List.
            cache.SetActivePage(0);
            //Apply tessellation to tessellated columns.
            cache.TessellateColumn("fPWD");

            //Add users to ListView control
            lstUsers.Clear();
            object[] _users = cache.GetObjectList("fUID");
            for (int i = 0; i < _users.Length; i++)
            {
                lstUsers.Items.Add(_users[i].ToString(), 1);
            }

            //Obtain the privilege list
            cache.SetActivePage(1);

            //Display it to the ComboBox Control
            txtPrivilege.Items.Clear();
            txtPrivilege.Items.AddRange(cache.GetObjectList("fData"));
        }
        //Initialize the CodeProcessor
        void InitCodeProc()
        {
            //Use this script to instantiate pre-defined programmable cores.
            CodeScript s = new CodeScript("INITPROC");

            //DB Unit
            s.Add(CodeIns.DBU_NEW_CORE);
            s.Add(CodeIns.DBU_END);
            //LF Unit
            s.Add(CodeIns.LFU_NEW_CORE);
            s.Add(CodeIns.LFU_END);
            //RF Unit
            s.Add(CodeIns.RFU_NEW_CORE);
            s.Add(CodeIns.RFU_END);

            proc.Run(s);
            
        }
        //Save Encoded Data
        void SaveUserData()
        {
            
            CodeScript s = new CodeScript("SAVE");
            object imgName = "''";

            s.Add(CodeIns.SYS_USE_CORE, 0);
            s.Add(CodeIns.DBU_CONNECT, Common.CFG.Read("DRIVER"), Common.CFG.Read("DB"),
                    Common.CFG.Read("UID"), Common.CFG.Read("PWD"), Common.CFG.Read("SERVER"));
            s.Add(CodeIns.DBU_BEGIN_TRANSACTION);
            //If the mode is Add New User
            if (isAddNew)
            {
                //Insert to user table
                
                if (hasImage) imgName = Sym.PQS(Common.CFG.Read("DB") + "/tblusers/" + txtUID.Text);
                s.Add(CodeIns.DBU_INSERT, "tblusers", new string[] { "fUID", "fPWD", "fPCount", "fImgName", "fName", "fContactNum", "fAddress", "fActivated", "fDesignation" },
                 new object[] { Sym.PQS(txtUID.Text), txtPWD.Text, Sym.PQS(lstPrivilege.Items.Count), imgName, 
                     Sym.PQS(txtName.Text), Sym.PQS(txtContactNum.Text), Sym.PQS(txtAddress.Text), Sym.PQS("1"), Sym.PQS(txtDesignation.Text)},
                 new bool[] { false, true, false, false, false, false, false, false, false});
                //Insert to privilege table
                for (int i = 0; i < lstPrivilege.Items.Count; i++)
                {
                    s.Add(CodeIns.DBU_INSERT, "tbluserprivilege", new string[] { "fUID", "fPrivilege" },
                     new object[] { Sym.PQS(txtUID.Text), lstPrivilege.Items[i]},
                     new bool[] { false, true });
                }
                
            }
            else
            {
                cache.SetActivePage(0);
                if (hasImage) imgName = Sym.PQS(Common.CFG.Read("DB") + "/tblusers/" + txtUID.Text);
                s.Add(CodeIns.DBU_UPDATE, "tblusers", new string[] { "fUID", "fPWD", "fPCount", "fImgName", "fName", "fContactNum", "fAddress", "fDesignation" },
                 new object[] { Sym.PQS(txtUID.Text), txtPWD.Text, Sym.PQS(lstPrivilege.Items.Count), imgName,
                     Sym.PQS(txtName.Text), Sym.PQS(txtContactNum.Text), Sym.PQS(txtAddress.Text), Sym.PQS(txtDesignation.Text)},
                     "(fID=" + Sym.PQS(cache.GetValue(userToEdit, "fID")) + ") AND (fStamp=" + Sym.PQS(Helper.ToMySQLDateTime(cache.GetValue(userToEdit, "fStamp"))) + ")",
                    new bool[] { false, true, false, false, false, false, false, false });
                //Check if privilege count is intact or not
                if (cachepriv.GetRecordCount(0) < lstPrivilege.Items.Count)
                {
                    //Case when the user Adds new privilege
                    //Update the remaining records to make sure that any changes are saved.
                    for (int i = 0; i < cachepriv.GetRecordCount(0); i++)
                    {
                        s.Add(CodeIns.DBU_UPDATE, "tbluserprivilege", new string[] { "fUID", "fPrivilege" },
                        new object[] { Sym.PQS(txtUID.Text), lstPrivilege.Items[i] },
                        "(fID=" + Sym.PQS(cachepriv.GetValue(i, "fID")) + ") AND (fStamp=" + Sym.PQS(Helper.ToMySQLDateTime(cachepriv.GetValue(i, "fStamp"))) + ")",
                        new bool[] { false, true });
                    }
                    //Insert the addtional records.
                    for (int i = cachepriv.GetRecordCount(0); i < lstPrivilege.Items.Count; i++)
                    {
                        s.Add(CodeIns.DBU_INSERT, "tbluserprivilege", new string[] { "fUID", "fPrivilege" },
                            new object[] { Sym.PQS(txtUID.Text), lstPrivilege.Items[i] },
                            new bool[] { false, true });
                    }

                }
                else if (cachepriv.GetRecordCount(0) > lstPrivilege.Items.Count)
                {
                    //Case when user remove privileges
                    //Update the remaining records to make sure that any changes are saved.
                    for (int i = 0; i < lstPrivilege.Items.Count; i++)
                    {
                        s.Add(CodeIns.DBU_UPDATE, "tbluserprivilege", new string[] { "fUID", "fPrivilege" },
                        new object[] { Sym.PQS(txtUID.Text), lstPrivilege.Items[i] },
                        "(fID=" + Sym.PQS(cachepriv.GetValue(i, "fID")) + ") AND (fStamp=" + Sym.PQS(Helper.ToMySQLDateTime(cachepriv.GetValue(i, "fStamp"))) + ")",
                        new bool[] { false, true });
                    }
                    //Delete the extra records.
                    for (int i = lstPrivilege.Items.Count; i < cachepriv.GetRecordCount(0); i++)
                    {
                        s.Add(CodeIns.DBU_DELETE, "tbluserprivilege", "(fID=" + Sym.PQS(cachepriv.GetValue(i, "fID")) + ") AND (fStamp=" + Sym.PQS(Helper.ToMySQLDateTime(cachepriv.GetValue(i, "fStamp"))) + ")");
                    }
                }
                else
                {
                    //if record count is retained, update all records to make sure all records are saved.
                    for (int i = 0; i < lstPrivilege.Items.Count; i++)
                    {
                        s.Add(CodeIns.DBU_UPDATE, "tbluserprivilege", new string[] { "fUID", "fPrivilege" },
                        new object[] { Sym.PQS(txtUID.Text), lstPrivilege.Items[i] },
                        "(fID=" + Sym.PQS(cachepriv.GetValue(i, "fID")) + ") AND (fStamp=" + Sym.PQS(Helper.ToMySQLDateTime(cachepriv.GetValue(i, "fStamp"))) + ")",
                        new bool[] { false, true });
                    }
                }
            }
            //Requery for the User table
            s.Add(CodeIns.DBU_QUERY, "SELECT fID, fStamp, fUID, fPWD, fPCount, fImgName, fName, fDesignation, fAddress, fContactNum FROM tblusers WHERE fActivated='1' ORDER BY fUID ASC");
            s.Add(CodeIns.DBU_QUERY, "SELECT fData FROM tbllookup WHERE fKey='PRIVILEGE' ORDER BY fData ASC");
            s.Add(CodeIns.DBU_END);

            //Send the file buffer to remote server
            if (hasImage)
            {
                s.Add(CodeIns.SYS_USE_CORE, 2);
                s.Add(CodeIns.RFU_SET_CONFIG, "ftp://" + Common.CFG.Read("SERVER"), Common.CFG.Read("UID"), Common.CFG.Read("PWD"), 256);
                s.Add(CodeIns.RFU_UPLD, Common.LOCPATH + CurrentUser.USERIDNUMBER + Const.USERMANAGERIMG, string.Format("{0}/{1}",
                    Common.CFG.Read("DB") + "/tblusers/", txtUID.Text));
                s.Add(CodeIns.RFU_END);
            }
            proc.Run(s);

        }
        //Deactivate an account.
        void DeactivateAccount()
        {
            DialogResult dlg  = Confirm.Generic("Deactivate Account", "If an account has been deactivated, it cannot be reactivated again.\r\nDo you wish to continue?",
                MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
            if (dlg == System.Windows.Forms.DialogResult.No) return;

            CodeScript s = new CodeScript("SAVE");
            s.Add(CodeIns.SYS_USE_CORE, 0);
            s.Add(CodeIns.DBU_CONNECT, Common.CFG.Read("DRIVER"), Common.CFG.Read("DB"),
                    Common.CFG.Read("UID"), Common.CFG.Read("PWD"), Common.CFG.Read("SERVER"));
            s.Add(CodeIns.DBU_BEGIN_TRANSACTION);
            s.Add(CodeIns.DBU_UPDATE, "tblusers", new string[] { "fActivated" }, new object[] { Sym.PQS("0") },
                "(fID=" + Sym.PQS(cache.GetValue(userToEdit, "fID")) + ") AND (fStamp=" + Sym.PQS(Helper.ToMySQLDateTime(cache.GetValue(userToEdit, "fStamp"))) + ")");
            //Requery for the User table
            s.Add(CodeIns.DBU_QUERY, "SELECT fID, fStamp, fUID, fPWD, fPCount, fImgName, fName, fAddress, fContactNum FROM tblusers WHERE fActivated='1' ORDER BY fUID ASC");
            s.Add(CodeIns.DBU_QUERY, "SELECT fData FROM tbllookup WHERE fKey='PRIVILEGE' ORDER BY fData ASC");
            s.Add(CodeIns.DBU_END);

            proc.Run(s);
        }
        //Load List Data.
        void LoadGUIData()
        {
            try
            {
                CodeScript s = new CodeScript("LOADPRIV");

                s.Add(CodeIns.SYS_USE_CORE, 0);
                s.Add(CodeIns.DBU_CONNECT, Common.CFG.Read("DRIVER"), Common.CFG.Read("DB"),
                        Common.CFG.Read("UID"), Common.CFG.Read("PWD"), Common.CFG.Read("SERVER"));

                s.Add(CodeIns.DBU_QUERY, "SELECT fID, fStamp, fUID, fPWD, fPCount, fImgName, fName, fDesignation, fAddress, fContactNum FROM tblusers WHERE fActivated='1' ORDER BY fUID ASC");
                if (isEditorMode) s.Add(CodeIns.DBU_QUERY, "SELECT fData FROM tbllookup WHERE fKey='PRIVILEGE' ORDER BY fData ASC");

                s.Add(CodeIns.DBU_END);
                proc.Run(s);
            }
            catch (Exception) { }
        }
        //Load the user's data from the database.
        void LoadUserData()
        {
            CodeScript s = new CodeScript("GETUSERDATA");
            s.Add(CodeIns.SYS_USE_CORE, 0);
            s.Add(CodeIns.DBU_CONNECT, Common.CFG.Read("DRIVER"), Common.CFG.Read("DB"),
                    Common.CFG.Read("UID"), Common.CFG.Read("PWD"), Common.CFG.Read("SERVER"));
            s.Add(CodeIns.DBU_QUERY, "SELECT fID, fStamp, fUID, fPrivilege FROM tbluserprivilege WHERE fUID=" + Sym.PQS(cache.GetValue(userToEdit, "fUID").ToString()));
            s.Add(CodeIns.DBU_END);

            if (cache.GetValue(userToEdit, "fImgName").ToString() != "")
            {
                hasImage = true;
                s.Add(CodeIns.SYS_USE_CORE, 2);
                s.Add(CodeIns.RFU_SET_CONFIG, "ftp://" + Common.CFG.Read("SERVER"), Common.CFG.Read("UID"), Common.CFG.Read("PWD"), 256);
                if (isEditorMode)
                    s.Add(CodeIns.RFU_DWLD, Common.LOCPATH + CurrentUser.USERIDNUMBER + Const.USERMANAGERIMG, cache.GetValue(userToEdit, "fImgName").ToString());
                else
                    s.Add(CodeIns.RFU_DWLD, Common.LOCPATH + Const.USERCURRENT, cache.GetValue(userToEdit, "fImgName").ToString());
            }
            s.Add(CodeIns.RFU_END);
            proc.SetOnErrorBehavior(OnErrorBehavior.ResumeNext);
            proc.Run(s);
        }
        //Show the user's data to the form or assign it as the current user.
        void ShowUserData()
        {
            if (isEditorMode)
            {
                txtUID.Text = cache.GetValue(userToEdit, "fUID").ToString();
                txtPWD.Text = cache.GetValue(userToEdit, "fPWD").ToString();
                lstPrivilege.Items.Clear();
                lstPrivilege.Items.AddRange(cachepriv.GetObjectList("fPrivilege"));
                if (hasImage)
                {
                    try
                    {
                        using (System.IO.Stream fs = System.IO.File.Open(Common.LOCPATH + CurrentUser.USERIDNUMBER + Const.USERMANAGERIMG, System.IO.FileMode.Open))
                        {
                            imgUser.Image = new Bitmap(fs);
                            fs.Close();
                        }
                    }
                    catch (Exception)
                    {
                        Confirm.Error("User Image", "There was a problem loading your user image.");
                        imgUser.Image = new Bitmap(480, 480);
                    }
                }
                txtName.Text = cache.GetValue(userToEdit, "fName").ToString();
                txtDesignation.Text = cache.GetValue(userToEdit, "fDesignation").ToString();
                txtAddress.Text = cache.GetValue(userToEdit, "fAddress").ToString();
                txtContactNum.Text = cache.GetValue(userToEdit, "fContactNum").ToString();
                grpUserDetails.Enabled = true;
            }
            else
            {
                CurrentUser.UID = cache.GetValue(userToEdit, "fUID").ToString();
                CurrentUser.ID = cache.GetValue(userToEdit, "fID");
                CurrentUser.NAME = cache.GetValue(userToEdit, "fName").ToString();
                CurrentUser.DESIGNATION = cache.GetValue(userToEdit, "fDesignation").ToString();
                CurrentUser.STAMP = cache.GetValue(userToEdit, "fStamp");
                CurrentUser.PWD = cache.GetValue(userToEdit, "fPWD").ToString();
                if (hasImage)
                {
                    try
                    {
                        using (System.IO.Stream fs = System.IO.File.Open(Common.LOCPATH + Const.USERCURRENT, System.IO.FileMode.Open))
                        {
                            CurrentUser.IMG = new Bitmap(fs);
                            fs.Close();
                        }
                    }
                    catch (Exception)
                    {
                        Confirm.Error("User Image", "There was a problem loading your user image.");
                        CurrentUser.IMG = new Bitmap(480, 480);
                    }
                }
                CurrentUser.PRIV = cachepriv.GetObjectList("fPrivilege");
                isAuthOk = true;
                if (LoginAuthCompleted != null) LoginAuthCompleted(null, null);
            }
        }
        //Clear User Fields
        void Clear()
        {
            //Clear fields
            txtUID.Text = "";
            txtPWD.Text = "";
            txtPrivilege.SelectedIndex = -1;
            lstPrivilege.Items.Clear();
            txtName.Text = "";
            txtDesignation.Text = "";
            txtAddress.Text = "";
            txtContactNum.Text = "";
            //Set the image into blank bitmap
            if (hasImage)
            {
                //imgUser.Image.Dispose();
                imgUser.Image = mes_tublay.Properties.Resources.DefaultProfile;
                hasImage = false;
            }

            
        }
        //Verify user credentials
        void VerifyCredentials()
        {
            //Assume Login mode
            bool _userfound = false;
            cache.SetActivePage(0);
            cache.TessellateColumn("fPWD");
            for (int i = 0; i < cache.GetRecordCount(0); i++)
            {
                if (cache.GetValue(i, "fUID").ToString().ToLower().Equals(_uid.ToLower()))
                {
                    _userfound = true;
                    if (cache.GetValue(i, "fPWD").ToString().Equals(_pwd))
                    {
                        //isAuthOk = true;
                        userToEdit = i;
                        LoadUserData();
                        break;
                    }//Password
                    else
                    {
                        if (LoginAuthCompleted != null) LoginAuthCompleted(null, null);
                    }
                }//Username
            }//For
            if (!_userfound) if (LoginAuthCompleted != null) LoginAuthCompleted(null, null);
        }
        /// <summary>
        /// Start the object in login mode.
        /// </summary>
        /// <param name="username">Username to check</param>
        /// <param name="password">Password to check</param>
        public void InitLogin(string username, string password)
        {
            _uid = username;
            _pwd = password;
            //Form is initialized
            isEditorMode = false;
            //Register Events
            DoCodeProcessor();
            //Initialize the CodeProcessor
            InitCodeProc();

        }
        /// <summary>
        /// Get the result of the login.
        /// </summary>
        /// <returns>boolean</returns>
        public bool LoginOk()
        {
            return isAuthOk;
        }
        /// <summary>
        /// Raised when login authentication is completed.
        /// </summary>
        public event EventHandler LoginAuthCompleted;
    }
}
